import { Component, OnInit , ViewChild  } from '@angular/core';
import { CommonService } from '../../service/common.service'
import { StorageService } from '../../service/storage.service'
import { Router , ActivatedRoute } from '@angular/router'
import { EventService } from '../../service/event.service'

@Component({
  selector: 'app-activate',
  templateUrl: './activate.page.html',
  styleUrls: ['./activate.page.scss'],
})
export class ActivatePage implements OnInit {

  @ViewChild('avatarInput') avatarInput;
  @ViewChild('copy') copy;

  public num:number;
  public address:string;
  public fileadd:string = ''
  public filearr:any[] = [];
  public flag:boolean = true;
  public show:boolean = false;
  public id:number
  public fileinfo:any
  public formData:any

  constructor(public common:CommonService,public activatedRoute:ActivatedRoute,private eventService:EventService,
    public storage:StorageService,private router:Router) { 

  }

  ngOnInit() {
    this.activatedRoute.queryParams.subscribe(data=>{
      this.id = data.id
    })

    this.filCostData()
  }

  dealImage(base64, w) {
    // var preview = document.getElementById("uploadimg");
    var newImage = new Image();
    var quality = 0.6;    //压缩系数0-1之间
    newImage.src = base64;
    newImage.setAttribute("crossOrigin", 'Anonymous');	//url为外域时需要
    var imgWidth, imgHeight;
    var that = this
    newImage.onload = function () {
        imgWidth = newImage.width;
        imgHeight = newImage.height;
        // console.log(imgWidth)
        // console.log(imgHeight)
        var canvas = document.createElement("canvas");
        var ctx = canvas.getContext("2d");
        if (Math.max(imgWidth, imgHeight) > w) {
            if (imgWidth > imgHeight) {
                canvas.width = w;
                canvas.height = w * imgHeight / imgWidth;
            } else {
                canvas.height = w;
                canvas.width = w * imgWidth / imgHeight;
            }
        } else {
            canvas.width = imgWidth;
            canvas.height = imgHeight;
            quality = 0.6;
        }
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        ctx.drawImage(newImage, 0, 0, canvas.width, canvas.height);
        var base64 = canvas.toDataURL("image/jpeg", quality); //压缩语句
        var newfile =  that.dataURLtoFile(base64,new Date().getTime()+'.jpeg');
        that.formData.append('file',newfile);
        that.aa()
    }
  }
  dataURLtoFile(dataurl, filename) { // base64转file对象
    var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
    while(n--){
        u8arr[n] = bstr.charCodeAt(n);
    }
    return new File([u8arr], filename, {type:mime});
  }

  changefile(e){
    this.show = true
    // 上传文件
    var fileList = this.avatarInput.nativeElement.files[0];
    this.formData = new FormData()
        var reader = new FileReader()
        reader.readAsDataURL(fileList);
        let size = fileList.size
        let that = this
        reader.onload = function(e) {
          if(that.filearr.length == 3){
            that.show = false
            that.common.presentToast("最多上传3张")
            return false
          }
          if(size > 1024 * 1024){
            that.dealImage(e.target.result,800)
          }else{
            that.formData.append('file', fileList)
            that.aa()
          }
        };
  }

  aa(){
    // 取消上传图
    var api = '/tbr/uploadImgs'
    this.common.postbody(api,this.formData).then((response:any)=>{
      // 加入数组
      if(response.code == 200){
        this.show = false
        this.filearr.push(response.data[0])
      }else{
        this.show = false
      }
      // console.log(this.filearr)
    })
  }

  changePhoto(e) {
    // 触发上传图片按钮
    this.avatarInput.nativeElement.dispatchEvent(new MouseEvent("click"))
  }

  // 获取Gas说明
  // /tbr/filCostData?userByLogId=订单记录id
  filCostData(){
    var api="/tbr/gas/filCostData?userByLogId="+this.id
    this.common.get(api).then((res:any)=>{
      console.log(res)
      if(res.code == 200){
        this.fileinfo = res.data
        this.fileadd = res.data.toAddress
      }
    })
  }

  onblur(){
    var patrn = /^\d+(\.\d+)?$/;
    if(!patrn.exec(this.num+'')){
      this.common.presentToast("请输入正确的金额")
      this.num = undefined
    }
  }

  // 确认充值
  confirm(){
    
    if(this.num == null || this.num < 0){
      this.common.presentToast("请输入正确金额")
      return false
    }
    if(this.filearr.length == 0){
      this.common.presentToast("请上传凭证")
      return false
    }
    this.show = true
    var path = '';
    for(var i=0;i<this.filearr.length;i++){
      if(i == this.filearr.length-1){
        path += this.filearr[i]
      }else{
        path += this.filearr[i]+','
      }
      
    }
    // debugger
    var api="/tbr/gas/submitFilTransfer";
    var params = {
      userByLogId:this.id,
      filCoin:this.num.toFixed(8),
      fromAddress:this.address,
      voucherImg:path
    }
    this.common.postbodys(api,params).then((res:any)=>{
      console.log(res)
      if(res.code == 200){
        this.show = false
        this.events()
        this.common.presentToast("已提交，待审核")
        this.router.navigate(['/mine/havestore'])
      }
    })
  }

  //通知用户中心更新用户信息
  events(){
    this.eventService.event.emit('useractive');
  }

  onCopy(){
    // alert(1)
    this.copy.nativeElement.select()
    // console.log(this.copy)               
    this.common.Clipboard.copy(this.copy.nativeElement.value)
  }




}
